在 Golang 中执行 net.DialTCP 时如何设置超时时间? 您所在的位置:网站首页 golang dial timeout 在 Golang 中执行 net.DialTCP 时如何设置超时时间?

在 Golang 中执行 net.DialTCP 时如何设置超时时间?

2023-04-21 12:58| 来源: 网络整理| 查看: 265

package main import ( "fmt" "net" "time" ) func main() { // Set the timeout to 5 seconds timeout := 5 * time.Second // Create a Dialer with the timeout set dialer := net.Dialer{ Timeout: timeout, } // DialTCP with the Dialer conn, err := dialer.DialTCP("tcp", nil, &net.TCPAddr{ IP: net.ParseIP("127.0.0.1"), Port: 8080, }) if err != nil { fmt.Println("Error:", err) return } // Do something with the connection fmt.Println("Connection established:", conn) }

在上面的示例代码中,我们创建了一个 Dialer,并将其 Timeout 字段设置为 5 秒。然后,我们使用该 Dialer 对 tcp 协议的 127.0.0.1:8080 进行拨号,如果成功,就会在标准输出中打印连接已经建立的消息。如果没有建立连接,则会在标准输出中打印错误消息。



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有